<template>
  <div class="chooseMaterials">
    <el-button
      v-if="showBtn"
      plain
      type="single-number-filleted"
      style="margin-left: 10px"
      @click="dialogFormVisible = true"
      >选择</el-button
    >
    <el-dialog
      width="920px"
      title="选择生产厂家/品牌"
      :visible.sync="dialogFormVisible"
      custom-class="sorting-code-number"
      :before-close="beforeClose"
    >
      <div class="el-dialog__body-bodys clearfix">
        <div class="bodys-header-top ccui-multifunctional-table-wrapper">
          <el-table
            ref="multipleTable2"
            height="152"
            :data="tableData2"
            highlight-current-row
            border
          >
            <el-table-column type="index" label="序号" width="50" />

            <el-table-column
              prop="manufacturerName"
              label="厂家名称"
              show-overflow-tooltip
            />

            <el-table-column
              prop="brandName"
              label="品牌名称"
              show-overflow-tooltip
            />

            <el-table-column label="操作">
              <template slot-scope="{ row, $index }">
                <el-button
                  size="mini"
                  type="text"
                  @click="tableData2RemoveRow(row, $index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="bodys-header-bottom">
          <div class="bodys-left">
            <div class="bodys-left-list">
              <div
                :class="[
                  'list-item',
                  { active: listItemIndex === item.concId }
                ]"
                v-for="item in leftListData"
                :key="item.concId"
                @click="handleClick(item)"
              >
                <i class="icon-ccui-deliver-goods" />
                <span
                  :class="[
                    'item-text',
                    { ellipsis: item.contractName.length >= 10 }
                  ]"
                  :title="item.contractName"
                  >{{ item.contractName }}</span
                >
                <i
                  v-show="
                    listItemIndex === item.concId && multipleSelection.length
                  "
                  class="icon-ccui-check"
                />
              </div>
            </div>
          </div>
          <div class="bodys-right">
            <div class="table-haeder">
              <el-search
                :formProp="searchFormData"
                @search="search"
                @change="change"
                :isShowSearch="true"
                :selectClear="true"
              >
                <template slot="search">
                  <el-input
                    v-model.trim="searchFormData.brandName"
                    clearable
                    searchLabel="品牌名称"
                    placeholder="请输入品牌名称模糊查询"
                  />

                  <el-input
                    v-model.trim="searchFormData.manufacturerName"
                    clearable
                    searchLabel="厂家名称"
                    placeholder="请输入厂家名称模糊查询"
                  />
                </template>
              </el-search>
            </div>

            <el-table
              ref="multipleTable"
              height="234"
              :data="tableData"
              :row-class-name="tableRowClassName"
              row-key="id"
              :header-cell-class-name="headerCellClass"
              style="width: 606.07px"
              highlight-current-row
              border
              @row-click="rowClick"
              @select="handleTableSelect"
              @select-all="handleTableSelectAll"
            >
              <el-table-column
                type="selection"
                width="55"
                reserve-selection
                :selectable="selectable"
              />

              <el-table-column
                prop="manufacturerName"
                label="厂家名称"
                show-overflow-tooltip
              >
                <template slot-scope="{ row }">
                  <span v-if="row.categoriesCode === '00'">其他: </span>
                  <span v-else>{{ row.manufacturerName }}</span>
                  <div @click.stop class="clickstop">
                    <el-input
                      style="width: 120px"
                      v-if="row.categoriesCode === '00'"
                      v-model="row.manufacturerName"
                      placeholder=""
                      maxlength="200"
                      @input="handleInputBlur(row)"
                    />
                  </div>
                </template>
              </el-table-column>

              <el-table-column
                prop="brandName"
                label="品牌名称"
                show-overflow-tooltip
              >
                <template slot-scope="{ row }">
                  <span v-if="row.categoriesCode === '00'">其他: </span>
                  <span v-else>{{ row.brandName }}</span>
                  <div @click.stop class="clickstop">
                    <el-input
                      style="width: 120px"
                      v-if="row.categoriesCode === '00'"
                      v-model="row.brandName"
                      placeholder=""
                      maxlength="200"
                      @input="handleInputBlur(row)"
                    />
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="操作">
                <template slot-scope="{ row, $index }">
                  <el-button
                    v-if="['00'].includes(row.categoriesCode) && $index === 0"
                    size="mini"
                    type="text"
                    @click.stop="addRow($index)"
                    >新增</el-button
                  >
                  <el-button
                    v-if="['00'].includes(row.categoriesCode) && $index !== 0"
                    size="mini"
                    type="text"
                    @click.stop="removeRow(row, $index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <div
              class="table-footer"
              style="height: 30px"
              v-show="tableData.length"
            >
              <div class="ccui-table-footer">
                <div id="ccui-paging">
                  <el-pagination
                    :total="pages.total"
                    :page-size="formData.pageSize"
                    :current-page="pages.pageNo"
                    prev-text="< 上一页"
                    next-text="下一页 >"
                    background
                    layout=" prev, pager, next, jumper"
                    popper-class="ccui-paging-page-size-popper"
                    @current-change="handleCurrentChange"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="default-mini" @click.stop="beforeClose"
          >取 消</el-button
        >
        <el-button size="mini" type="primary-font-mini" @click.stop="confirm"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { generateUUID } from "@/basa/utils";
export default {
  name: "chooseStatement",
  props: {
    // 是否显示按钮
    showBtn: {
      type: Boolean,
      default: false
    },
    // 左侧数据
    setContractList: {
      type: Array,
      default: () => []
    },
    // 右侧数据
    setTableList: {
      type: Array,
      default: () => []
    },
    // 行参数
    rowParams: {
      type: Object,
      default: () => {}
    },
    pages: {
      type: Object,
      default: () => {}
    },
    // 回显数组
    selectData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      tableData: [],
      formData: {
        pageNo: 1,
        pageSize: 10,
        catalogId: ""
      },
      searchFormData: {
        manufacturerName: "",
        brandName: ""
      },
      materialsData: "", // 选择数据
      isTurnPage: false, //是否有翻页
      keyWord: "",
      contractList: [
        { concId: "01", contractName: "钢材" },
        { concId: "02", contractName: "水泥" },
        { concId: "03", contractName: "沥青" },
        { concId: "04", contractName: "燃油" },
        { concId: "00", contractName: "其他" }
      ],
      leftListData: [],
      listItemIndex: 1,
      radioSelect: "",
      sendLeftParams: {},
      multipleSelection: [],
      multipleSelectionNames: [],
      tableData2: [],
      beforeSelectData: [],
      toggleCheckbox: true,
      isShow: true,
      removeRowIdArr: []
    };
  },
  watch: {
    // 获取左侧列表 (预留)
    // setContractList(newVal) {
    //   this.leftListData = newVal;
    // },
    // 获取结算单列表
    setTableList: {
      deep: true,
      handler(newVal) {
        this.tableData = newVal.map(n => ({
          ...n,
          manufacturerName:
            n.manufacturerName === "其他" ? "" : n.manufacturerName,
          brandName: n.brandName === "其他" ? "" : n.brandName
        }));

        // 回显
        if (this.selectData.length) {
          this.$nextTick(() => {
            this.tableData2.map(n => {
              this.tableData.map(m => {
                if (
                  (n.manufacturerName !== "" &&
                    n.manufacturerName === m.manufacturerName) ||
                  (n.brandName !== "" && n.brandName === m.brandName)
                ) {
                  this.$refs.multipleTable.toggleRowSelection(m, true);
                }
              });
            });

            if (this.isShow) this.tableData2 = this.selectData;
          });
        }
        if (this.removeRowIdArr.length) {
          this.$nextTick(() => {
            this.removeRowIdArr.map(n => {
              this.tableData.map(m => {
                if (
                  (n.manufacturerName !== "" &&
                    n.manufacturerName === m.manufacturerName) ||
                  (n.brandName !== "" && n.brandName === m.brandName)
                ) {
                  this.$refs.multipleTable.toggleRowSelection(m, false);
                }
              });
            });
          });
        }

        // 重新布局
        this.$nextTick(() => {
          this.$refs.multipleTable.doLayout();
        });
      }
    }
  },
  methods: {
    init() {
      if (Object.keys(this.rowParams).length) {
        this.leftListData = [
          ...this.contractList.filter(
            _ => _.concId === this.rowParams.firstCategoriesOfCode
          ),
          { concId: "00", contractName: "其他" }
        ];
      } else {
        // this.leftListData = this.contractList;
        this.leftListData = [{ concId: "00", contractName: "其他" }];
      }
      this.tableData2 = this.selectData;
      this.listItemIndex = this.leftListData[0].concId;
    },
    // 切换左侧合同
    handleClick(val) {
      if (this.listItemIndex === val.concId) return;
      this.listItemIndex = val.concId;
      this.sendLeftParams = val;
      this.multipleSelection = [];
      this.radioSelect = "";
      this.isShow = false;

      this.searchFormData = {
        manufacturerName: "",
        brandName: ""
      };
      // this.$refs.multipleTable.clearSelection();
      this.$emit("autocompleteSelect", { ...val, type: "leftList" });
    },
    // 每页条数发生改变
    handleSizeChange(val) {
      this.pageNoCode = 1;
      this.$emit("autocompleteSelect", { pageSize: val, type: "pageSize" });
    },
    // 当前页发生改变
    handleCurrentChange(val) {
      this.formData.pageNo = val;
      this.isShow = false;
      this.$emit("autocompleteSelect", { pageNo: val, type: "pageNo" });
    },

    // 关闭弹窗
    beforeClose() {
      this.dialogFormVisible = false;
      this.handleReset();
    },

    // 确认并发送数据
    confirm() {
      if (!this.tableData2.length) {
        return this.$showErrorMessage("未选择数据，请重试");
      }
      this.$emit("ok", this.tableData2);
      this.handleReset();
      this.dialogFormVisible = false;
    },

    // 重置
    handleReset() {
      this.listItemIndex = 1;
      this.multipleSelection = [];
      this.leftListData = [];
      this.radioSelect = "";
      this.tableData = [];
      this.tableData2 = [];
      this.isShow = true;

      this.searchFormData = {
        manufacturerName: "",
        brandName: ""
      };

      this.$refs.multipleTable.clearSelection();
      this.$emit("autocompleteSelect", { type: "reset" });
    },

    handleSelect(val) {
      this.keyWord = val.contractName;
      this.listItemIndex = val.concId;
      this.$emit("autocompleteSelect", val);
    },

    // 为禁用行添加样式
    tableRowClassName({ row, rowIndex }) {
      if (row.currentAccumulatedunPaiedAmt === 0) {
        return "prohibit";
      }
    },

    // Todo 高级搜索所需函数 start
    search(searchData) {
      this.pageNoCode = 1;
      this.$emit("autocompleteSelect", {
        searchData: this.searchFormData,
        type: "search"
      });
    },

    change(index, key, value) {
      const formDataKeys = Object.keys(this.searchFormData);
      formDataKeys.map(_ => {
        if (_ !== key) {
          this.searchFormData[_] = "";
          this.$emit("autocompleteSelect", {
            changeNode: _,
            type: "formChange"
          });
        }
      });
    },

    handleTableSelect(selection, row) {
      this.tableData2 = [...this.tableData2, row];
      this.removeRowIdArr = this.removeRowIdArr.filter(
        n =>
          (n.manufacturerName !== "" &&
            n.manufacturerName !== row.manufacturerName) ||
          (n.brandName !== "" && n.brandName !== row.brandName)
      );
      if (!selection.includes(row)) {
        this.tableData2 = this.tableData2.filter(
          item =>
            (item.manufacturerName !== "" &&
              item.manufacturerName !== row.manufacturerName) ||
            (item.brandName !== "" && item.brandName !== row.brandName)
        );
      }
    },

    handleTableSelectAll(selection) {
      this.tableData2 = [];
      // const indexArr = [];
      let arr = selection.length ? selection : this.tableData;
      let obj = [...this.selectData];
      obj.map(n => {
        arr.map(m => {
          if (
            (n.manufacturerName !== "" &&
              n.manufacturerName === m.manufacturerName) ||
            (n.brandName !== "" && n.brandName === n.brandName)
          ) {
            obj = obj.filter(
              item =>
                (item.manufacturerName !== "" &&
                  item.manufacturerName !== m.manufacturerName) ||
                (item.brandName !== "" && item.brandName !== m.brandName)
            );
            // indexArr.push(
            //   obj.findIndex(
            //     item => item.manufacturerName === m.manufacturerName
            //   )
            // );
          }
        });
      });
      // console.log(">>>>>>>>", indexArr, "<<<<<<<<");

      this.$emit("update:selectData", obj);

      this.tableData2 = [...obj, ...selection];

      this.removeRowIdArr.map(n => {
        this.tableData.map(m => {
          if (
            (n.manufacturerName !== "" &&
              n.manufacturerName === m.manufacturerName) ||
            (n.brandName !== "" && n.brandName === m.brandName)
          ) {
            this.removeRowIdArr = this.removeRowIdArr.filter(
              n =>
                (n.manufacturerName !== "" &&
                  n.manufacturerName !== m.manufacturerName) ||
                (n.brandName !== "" && n.brandName !== m.brandName)
            );
          }
        });
      });

      this.removeRowIdArr.map(n => {
        this.tableData2 = this.tableData2.filter(
          item =>
            (item.manufacturerName !== "" &&
              item.manufacturerName !== n.manufacturerName) ||
            (item.brandName !== "" && item.brandName !== n.brandName)
        );
      });
    },

    // 点击行单选
    rowClick(row, event, column) {
      // if (row.categoriesCode === "00") return;
      // const isExist = this.tableData2.map(n => n.id).includes(row.id);
      // const selection = this.$refs.multipleTable.selection;
      // this.removeRowIdArr = this.removeRowIdArr.filter(
      //   n => n.manufacturerName !== row.manufacturerName
      // );
      // if (selection.includes(row)) {
      //   this.tableData2 = this.tableData2.filter(
      //     item => item.manufacturerName !== row.manufacturerName
      //   );
      // } else {
      //   this.tableData2.push(row);
      // }
      // this.$refs.multipleTable.toggleRowSelection(row, !isExist);
    },

    // 新增'其他'行
    addRow(index) {
      const i = this.tableData.filter(_ => _.categoriesCode === "00").length;
      this.tableData.splice(i, 0, {
        categoriesCode: "00",
        manufacturerName: "",
        manufacturerCode: "其他",
        brandName: "",
        id: generateUUID()
      });
    },

    // 删除'其他'行
    removeRow(row, index) {
      this.tableData.splice(index, 1);
      this.tableData2RemoveRow(row, index);
    },

    // 删除顶部的数据
    tableData2RemoveRow(row, index) {
      this.removeRowIdArr.push(row); // bug(23903) 选择生产厂家后点击删除按钮，再点击全选按钮，删除的选项又回来了

      this.tableData2 = this.tableData2.filter(
        item =>
          (item.manufacturerName !== "" &&
            item.manufacturerName !== row.manufacturerName) ||
          (item.brandName !== "" && item.brandName !== row.brandName)
      );

      this.$nextTick(() => {
        this.tableData.map(n => {
          if (
            (row.manufacturerName !== "" &&
              row.manufacturerName === n.manufacturerName) ||
            (row.brandName !== "" && row.brandName === n.brandName)
          ) {
            this.$refs.multipleTable.toggleRowSelection(n, false);
          }
        });
      });
    },

    // 禁用未填写的'其他'行
    selectable(row) {
      if (row.manufacturerName || row.brandName) {
        this.toggleCheckbox = true;
        return true;
      } else {
        this.toggleCheckbox = false;
        return false;
      }
    },

    // 失去焦点删除已选择的'其他'行
    handleInputBlur(row) {
      if (
        row.categoriesCode === "00" &&
        !row.manufacturerName &&
        !row.brandName &&
        this.tableData2.length
      ) {
        this.tableData2RemoveRow(row);
      }
    },

    headerCellClass({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        return this.toggleCheckbox ? "show-checkbox" : "hide-checkbox";
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.chooseMaterials {
  display: inline-block;
}
/deep/ .sorting-code-number {
  .el-search .ccui-search-wrapper {
    margin-top: 15px;
  }
  // min-height: 660px;
  .ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .el-dialog__body {
    box-sizing: border-box;
    padding-top: 20px;
    padding-bottom: 20px;
    width: 914px;
    height: inherit;
    // max-height: 80vh;
    .el-dialog__body-bodys {
      height: 83%;
      .bodys-left {
        overflow-x: hidden;
        box-sizing: border-box;
        width: 245px;
        margin-top: 60px;
        .el-input {
          width: 205px;
        }
        .bodys-left-list {
          padding: 20px;
          .list-item {
            display: flex;
            align-items: center;
            padding-left: 10px;
            padding-right: 5px;
            line-height: 35px;
            font-size: 13px;
            cursor: pointer;
            transition: 0.2s;
            &:hover,
            &.active {
              background-color: #e5f4ff;
              color: #0089ef;
            }
            .item-text {
              padding: 0 10px;
            }
          }
        }
      }
      .bodys-right {
        .el-table {
          .el-radio__label {
            padding-left: 12px;
          }
          .prohibit {
            cursor: not-allowed;
          }
          .show-checkbox .cell {
            display: block;
          }
          .hide-checkbox .cell {
            display: none;
          }
        }
      }
      .ccui-multifunctional-table-wrapper .el-table tbody tr:last-child td {
        border-bottom: 1px solid #f1f1f1;
      }
    }
  }
}
.autocomplete-item {
  display: flex;
  align-items: center;
  span {
    padding: 0 10px;
  }
}
.clickstop {
  display: inline-block;
}
</style>
